use rand::{self, Rng};
use std::{
    thread::{self},
    time::Duration,
};

struct Person {
    name: String,
}

impl Person {
    fn new(name: &str) -> Person {
        Person {
            name: name.to_string(),
        }
    }

    fn eat(&self) {
        let mut rng = rand::thread_rng();
        println!("{}正在吃饭线程id-{:?}", self.name, thread::current().id());
        thread::sleep(Duration::from_secs(rng.gen_range(1..10)));
        println!("{}吃好了,线程id-{:?}", self.name, thread::current().id());
    }
}

fn main() {
    let persons = vec![
        Person::new("张三"),
        Person::new("李四"),
        Person::new("周五"),
        Person::new("王八"),
    ];
    //多线程
    let handles: Vec<_> = persons
        .into_iter()
        .map(|p| {
            thread::spawn(move || {
                p.eat();
            })
        })
        .collect();
    //保证每个任务都执行了
    for h in handles {
        h.join().unwrap()
    }
}
